import { createSlice } from "@reduxjs/toolkit"
import {removeToken} from '../../utils'
import { setToken as _setToken , getToken } from "../../utils"
import { getProfileAPI, loginAPI } from "../../apis/user"
const userStore =  createSlice({
    name:'user',
    initialState: {
        token: getToken() || '',
        userInfo:{}
    },
    reducers: {
        setToken(state,action){
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearuserInfo(state) {
            state.token = '',
            state.userInfo = {},
            removeToken()
        }
    },
    
})


const {setToken , setUserInfo , clearuserInfo} = userStore.actions

const fetchLosin = (loginForm)=> {
    return async (dispatch)=> {
        const res = await loginAPI(loginForm)
        dispatch(setToken(res.data.token))
    }
}

const fetchUserInfo = ()=> {
    return async (dispatch)=> {
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}



export {setToken , fetchLosin , fetchUserInfo , clearuserInfo}

export default userStore.reducer

